package utils;

import models.cms.Resource;
import org.apache.commons.io.FileUtils;
import play.data.Upload;
import swagger.annotations.ApiInfo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * Created by nileb on 2015/12/17.
 */
public class ResourceUtils {

    public static Resource process(Upload file) {
        try {
            Resource resource = new Resource();
            resource.content_type = file.getContentType();
            resource.name = file.getFileName();
            resource.size = file.getSize();
            resource.created_at = new Date();
            resource.type = Resource.ResourceType.detect(resource.content_type);
            resource.user = SessionUtils.getCurrentUser();
            resource.hash = UUID.randomUUID().toString();
            resource.save();
            FileUtils.copyFile(file.asFile(), new File("upload", resource.hash));
            ImgUtils.thumbnail(new File("upload", resource.hash), new File("upload", resource.hash + "_t"));
            return resource;
        } catch (Exception e) {
            throw new RuntimeException("处理资源出错", e);
        }
    }

    public static InputStream open(Resource res, String type) throws IOException {
        type = type == null ?  "": type;
        String postfix = "";
        switch (type) {
            case "thumb":
                postfix = "_t";
                break;
            default:
                postfix = "";
        }
        File file = new File("upload", res.hash + postfix);
        if (!file.exists()) {
            ImgUtils.thumbnail(new File("upload", res.hash), file);
        }
        return FileUtils.openInputStream(file);
    }
}
